<template>
  <div class="user-info-container">
    <!-- 添加加载状态和空状态处理 -->
    <template v-if="loading">
      <el-skeleton :rows="5" animated />
    </template>
    <template v-else-if="!userData">
      <el-empty description="未获取到用户信息" />
    </template>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="editMode = true" v-if="!editMode">编辑</el-button>
        </div>
      </template>

      <el-form :model="userForm" label-width="100px" v-if="!editMode">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.phone" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" disabled></el-input>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-input v-model="userForm.createTime" disabled></el-input>
        </el-form-item>
      </el-form>

      <el-form :model="userForm" label-width="100px" :rules="rules" ref="formRef" v-else>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <div style="text-align: right;">
          <el-button @click="editMode = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      <el-form :model="passwordForm" label-width="100px" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password"></el-input>
        </el-form-item>
        <div style="text-align: right;">
          <el-button type="primary" @click="submitPasswordForm">修改密码</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from "axios";
import {useRouter} from "vue-router";

const router = useRouter();
const loading = ref(true);
const userData = ref(null); // 改为明确的null初始化

const editMode = ref(false);
const userForm = ref({
  username: '',
  phone: '',
  email: '',
  createTime: ''
});

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
};

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
};

function validatePassword(rule, value, callback) {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true;

    // 优先检查本地存储
    const localUser = localStorage.getItem('user');
    if (localUser) {
      userData.value = JSON.parse(localUser);
    }

    // 强制从接口获取最新数据
    const response = await axios.get(`${BASE_URL}/v1/user/info`, {
      withCredentials: true
    });

    if (response.data?.data) {
      userData.value = response.data.data;
      localStorage.setItem('user', JSON.stringify(response.data.data));
    } else {
      throw new Error('无效的用户数据');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);

    // 根据错误状态处理
    if (error.response?.status === 401) {
      ElMessage.warning('请重新登录');
      localStorage.removeItem('user');
      router.push('/login');
    } else {
      ElMessage.error('获取用户信息失败');
    }
  } finally {
    loading.value = false;
  }
};

const submitForm = async () => {
  try {
    await axios.put(BASE_URL+'v1/user/info', userForm.value);
    ElMessage.success('信息更新成功');
    editMode.value = false;
    fetchUserInfo();
  } catch (error) {
    ElMessage.error(error.response.data.message || '更新失败');
  }
};

const submitPasswordForm = async () => {
  try {
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      ElMessage.error('两次输入密码不一致');
      return;
    }

    await axios.post(BASE_URL+'/v1/user/password', {
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    });

    ElMessage.success('密码修改成功');
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    };
  } catch (error) {
    ElMessage.error(error.response.data.message || '密码修改失败');
  }
};

onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
.user-info-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>